package com.turing.post.datatranfer.impl;

import java.util.List;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.datatranfer.util.ActivateCard;
import com.turing.post.datatranfer.util.ActivateCardDao;

@Stateless(mappedName = "datatranfer.impl.ActivateCardDaoImpl")
@Remote
@Local
public class ActivateCardDaoImpl implements ActivateCardDao {

	/**
	 * 实体管理器
	 */
	@PersistenceContext
	protected EntityManager _em;

	/**
	 * 按照分页获取激活卡序号,插入map表中
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<ActivateCard> getOldActivateCardSeqNo() {
		String sql = "select t.cardseqno from activatecard t order by t.cardseqno";
		Query query = _em.createNativeQuery(sql, ActivateCard.class);
		List<ActivateCard> list = query.getResultList();
		return list;
	}

	/**
	 * 根据卡序号获取旧系统中激活卡信息
	 * 
	 */
	@Override
	public ActivateCard getOldActivateCardBySeqNo(String cardSeqNo) {
		String sql = "select * from activatecard t where t.cardseqno=?1";
		Query query = _em.createNativeQuery(sql, ActivateCard.class);
		query.setParameter(1, cardSeqNo);
		return (ActivateCard) query.getSingleResult();
	}

	/**
	 * 获取最小卡序号 初始化中使用
	 */
	@Override
	public String getMinCardSeqNoFromOldActivateCard(String batchNo) {
		String sql = "select min(t.cardseqno) from activatecard t where t.batchno =?1";
		Query query = _em.createNativeQuery(sql);
		query.setParameter(1, batchNo);
		return (String) query.getSingleResult();
	}

	/**
	 * 从老系统找比这个最大卡顺序号大的最小的卡顺序号
	 * 
	 * @param cardSeqNo
	 * @return
	 */
	@Override
	public String getMinOldActivateCardBySeqNo(String cardSeqNo) {
		String sql = "select min(t.cardseqno) from activatecard t where t.cardseqno>?1";
		Query query = _em.createNativeQuery(sql);
		query.setParameter(1, cardSeqNo);
		return (String) query.getSingleResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Object[]> getBatchNoFromOldActivateCard() {
		String sql = "select distinct(t.batchno),count(t.cardseqno) from activatecard t group by t.batchno order by 2 desc";
		Query query = _em.createNativeQuery(sql);
		return query.getResultList();
	}

	@Override
	public int getOldActivateCardTotalCount(String batchNo) {
		String sql = "select nvl(count(*),0) from activatecard t where t.batchno = ?1";
		Query query = _em.createNativeQuery(sql);
		query.setParameter(1, batchNo);
		return Integer.parseInt(query.getSingleResult().toString());
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ActivateCard> getOldActivateCardByBatchNo(String batchNo) {
		String sql = "select t.* from activatecard t where t.batchno = ?1";
		Query query = _em.createNativeQuery(sql, ActivateCard.class);
		query.setParameter(1, batchNo);
		return query.getResultList();
	}

}
